package edu.zut.main.thread;

public class TicketDemo {
    public static void main(String[] args) {
        Sale sale = new Sale();
        SaleTicketThread saleTicketThread = new SaleTicketThread(sale);
        SaleTicketThread saleTicketThread2 = new SaleTicketThread(sale);
        SaleTicketThread saleTicketThread3 = new SaleTicketThread(sale);

        new Thread(saleTicketThread,"小花").start();
        new Thread(saleTicketThread2,"小明").start();
        new Thread(saleTicketThread3,"小李子").start();

    }

}
//售票线程
class SaleTicketThread implements Runnable{

    private Sale sale;

    public SaleTicketThread(Sale sale) {
        this.sale = sale;
    }

    @Override
    public void run() {
        //售票任务
        while (true){
            //售票的操作我们要保证同一时刻只能由一个线程执行，不管有无阻塞
//            synchronized (sale){
                if (sale.getTicketNum() <= 0) {
                    System.out.println(Thread.currentThread().getName() + "余票不足");
                    break;
                }
                sale.saleTicket();
//            }
        }
    }
}

//售票操作
class Sale{
    //余票
    private int ticketNum = 10;
    //为了保证获取余票的操作在某一时刻只能由一个线程使用，不管这个线程是否出现阻塞，可以使用同步方法
    public synchronized int getTicketNum() {
        return ticketNum;
    }

    //售票方法
    //卖票的过程也需要保证同一时刻只能由一个线程访问,也可以在此添加同步关键字
    //同步方法的本质是锁定当前对象
    public synchronized void saleTicket(){
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "售出了第" + ticketNum + "张票");
        ticketNum--;
    }
}